
/** 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.tompai.common.lock;

/**
* @desc: tompai-common
* @name: MakeLock.java
* @author: tompai
* @email：liinux@qq.com
* @createTime: 2021年2月7日 下午11:37:47
* @history:
* @version: v1.0
*/

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MakeLock implements Runnable {
	private String threadID = "";

	public void run() {
		try {
			while (true) {
				test2(threadID);
				Thread.sleep(200);
			}
		} catch (IOException e) {
			System.out.println(e);
			e.printStackTrace();
		} catch (InterruptedException e) {
			System.out.println(e);
		}
	}

	public void test2(String threadID) throws FileNotFoundException, IOException, InterruptedException {
		Lock lock = new MakeLock(threadID).getLock("E:\\TMP\\123.txt", threadID);
		System.out.println(threadID + ":obtain...");
		boolean b = lock.obtain();
		//当有重叠时会发生等待，所以外侧先执行isLocked()判断
		System.out.println(threadID + ":obtained   " + b);
		if (b) {// 执行业务逻辑
			Thread.sleep(390);
			for (int i = 0; i < Integer.MAX_VALUE; i++) {
				;
			}
			lock.unlock();
		}
		lock = null;

	}

	public MakeLock(String threadID) {
		this.threadID = threadID;
	}

	public Lock getLock(String name, String threadID) {
		final StringBuffer buf = new StringBuffer();
		return FileProgrameLock.get(name, threadID);
	}

}
